package com.patrol.patrol.ui.appear;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.patrol.patrol.MyApplication;
import com.patrol.patrol.R;
import com.patrol.patrol.data.EventImgModel;
import com.patrol.patrol.data.EventModel;
import com.patrol.patrol.data.KeyValueInfo;
import com.patrol.patrol.ui.BaseActivity;
import com.patrol.patrol.utils.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhaoss.weixinrecorded.activity.RecordedActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = "/app/AppearActivity")
public class AppearActivity extends BaseActivity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_num)
    EditText etNum;
//    @BindView(R.id.et_school)
//    EditText etSchool;
    @BindView(R.id.sp_sex)
    Spinner spSex;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.grid_exp)
    ExpandableGridView gridExp;
    @BindView(R.id.img_camera)
    ImageView imgCamera;
    @BindView(R.id.tv_update)
    TextView tvUpdate;

    ImageAdapter adapter;
    List<ImageInfo> imageInfos;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    @Autowired(name = "eventModelJson")
    String eventModelJson;

    EventModel eventModel;

    public static List<KeyValueInfo> spSexDataList = new ArrayList();

    static{
        spSexDataList = new ArrayList(){{
            add(new KeyValueInfo("1","军容风纪"));
            add(new KeyValueInfo("2","环境卫生"));
            add(new KeyValueInfo("3","内务队列"));
            add(new KeyValueInfo("4","超速乱停"));
            add(new KeyValueInfo("5","其他"));
        }};
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appear);
        ButterKnife.bind(this);
        imageInfos = new ArrayList<>();
        tvTitle.setText("编辑数据");

        adapter = new ImageAdapter(imageInfos, mContext, new ImageAdapter.OnItemDeleteClick() {
            @Override
            public void onItemDeleteClick(int position) {
                imageInfos.remove(position);
                adapter.notifyDataSetChanged();
            }
        }, new ImageAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {

            }
        });
        gridExp.setAdapter(adapter);

        eventModel = new Gson().fromJson(eventModelJson,EventModel.class);

        long eventId = eventModel.getPrimaryKey();

        List<EventImgModel> imgModelList = MyApplication.dbProxy.queryListBySql(EventImgModel.class,"select * from event_img_model where event_id = " + eventId);

        if(null != imgModelList && imgModelList.size()>0){
            imgModelList.forEach(img->{
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setImageType(img.getImageType());
                imageInfo.setImageUrl(img.getImageUrl());
                imageInfos.add(imageInfo);
            });
        }

        etName.setText(eventModel.getEtName());
        etNum.setText(eventModel.getEtNum());
//        etSchool.setText(eventModel.getEtSchool());
        etRemark.setText(eventModel.getEtRemark());

        ArrayAdapter<KeyValueInfo> arrayAdapter = new ArrayAdapter<KeyValueInfo>(this, android.R.layout.simple_spinner_dropdown_item, spSexDataList);
        spSex.setAdapter(arrayAdapter);

        for(int i=0;i<spSexDataList.size();i++){
            if(eventModel.getSpSex().equals(spSexDataList.get(i).getKey())){
                spSex.setSelection(i,true);
                break;
            }
        }
    }

    @OnClick({R.id.img_camera, R.id.tv_update,R.id.tv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_camera:
                AndPermission.with(mContext).permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .requestCode(0).callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        Intent intent = new Intent(mContext, RecordedActivity.class);
                        startActivityForResult(intent, 1);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    }
                }).start();
                break;
            case R.id.tv_update:
                ToastUtils.showToast("确定");
                MyApplication.dbProxy.delete(EventImgModel.class,"event_id = ?","" + eventModel.getPrimaryKey());
                EventModel model = new EventModel();
                model.setEtName(etName.getText().toString())
                        .setEtNum(etNum.getText().toString())
//                        .setEtSchool(etSchool.getText().toString())
                        .setSpSex(((KeyValueInfo)(spSex.getSelectedItem())).getKey())
                        .setEtRemark(etRemark.getText().toString())
                        .setTime(eventModel.getTime())
                        .setPrimaryKey(eventModel.getPrimaryKey());
                MyApplication.dbProxy.update(model);
                if(null != imageInfos && imageInfos.size()>0){
                    List<EventImgModel> imgModelList = new ArrayList<>();
                    for(ImageInfo imageInfo:imageInfos){
                        EventImgModel imgModel = new EventImgModel();
                        imgModel.setEventId(model.getPrimaryKey());
                        imgModel.setImageType(imageInfo.getImageType());
                        imgModel.setImageUrl(imageInfo.getImageUrl());
                        imgModelList.add(imgModel);
                    }
                    MyApplication.dbProxy.insert(imgModelList);
                }
                this.finish();
                break;
            case R.id.tv_del:
                ToastUtils.showToast("删除");
                MyApplication.dbProxy.delete(EventModel.class,eventModel.getPrimaryKey());
                MyApplication.dbProxy.delete(EventImgModel.class,"event_id = ?","" + eventModel.getPrimaryKey());
                this.finish();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == 1) {
//                textureView.setVisibility(View.GONE);
//                iv_photo.setVisibility(View.GONE);
                int dataType = data.getIntExtra(RecordedActivity.INTENT_DATA_TYPE, RecordedActivity.RESULT_TYPE_VIDEO);
                if (dataType == RecordedActivity.RESULT_TYPE_VIDEO) {
                    String videoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("视频地址: "+videoPath);
//                    textureView.setVisibility(View.VISIBLE);
//                    playVideo(videoPath);
                    imageInfos.add(new ImageInfo().setImageUrl(videoPath).setImageType(RecordedActivity.RESULT_TYPE_VIDEO));
                } else if (dataType == RecordedActivity.RESULT_TYPE_PHOTO) {
                    String photoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("图片地址: "+photoPath);
//                    iv_photo.setVisibility(View.VISIBLE);
//                    iv_photo.setImageBitmap(BitmapFactory.decodeFile(photoPath));
                    imageInfos.add(new ImageInfo().setImageUrl(photoPath).setImageType(RecordedActivity.RESULT_TYPE_PHOTO));
                }

                adapter.notifyDataSetChanged();
            }
        }
    }
}
